package com.kgc.scd.controller;


import com.kgc.scd.annotation.TokenPermission;
import com.kgc.scd.bean.UserVO;
import com.kgc.scd.conntant.WechatPayConstant;
import com.kgc.scd.service.WechatPayService;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Created On : 2022/11/4.
 * <p>
 * Author : #jiangguoqiang
 * <p>
 * Description: 微信支付接口的操作入口
 */
@Slf4j
@RestController
@Api(tags = "购买会员")
public class WechatPayController {

    @Autowired
    private WechatPayService wechatPayService;
    /**
     * @author : Administrator
     * @date   : 2022/11/4
     * @param  : []
     * @return : com.kgc.sct.util.RequestResult<java.util.Map<java.lang.String,java.lang.Object>>
     * @description : 请求微信统一下单接口，下预支付订单，返回支付连接
     */
    @PostMapping("/unifyOrder")
    @ApiOperation(value = "微信支付购买会员",notes = "基于微信支付购买会员")
    @TokenPermission
    public RequestResult<Map<String,String>> wechatPayUnifyOrder(@RequestHeader String token, @RequestParam(value = "购买会员几个月",required = false) Integer num) throws Exception {

        String productBody = "购买会员";
        int totalFee = 1;
        if (num != null){
            totalFee = 1*num;
        }
        //调用业务接口，生成请求微信支付接口，统一下的完整参数，xml格式的，微信支付接口要求
        String unifyOrderXmlParams = wechatPayService.generateWxpayUnitfyOrderXmlParams(productBody,totalFee,token);

        log.info("请求微信统一下单接口参数：{}",unifyOrderXmlParams);

        // 调用业务接口，请求为西南支付统一下单接口，获取下单结果
        Map<String,String> unifyOrderMapResult = wechatPayService.getWechatPayUnifyOrderResult(unifyOrderXmlParams);

        log.info("2.请求微信支付统一接口返回：{}",unifyOrderMapResult);

        //定义当前接口返回的Map集合
        Map<String,String> resultMap = new HashMap<>();

        // 解析微信支付统一下单结果，如果下单成功，获取用户进行扫码支付的连接，返回给前端，生成二维码，扫码支付
        if (WechatPayConstant.WECHAT_PAY_RESULT_SUCCESS.equals(unifyOrderMapResult.get("return_code"))
            && WechatPayConstant.WECHAT_PAY_RESULT_SUCCESS.equals(unifyOrderMapResult.get("result_code"))){
            //微信支付统一下单成功，省略签名校验

            //获取成功的结果

            //交易类型
            resultMap.put("trade_type",unifyOrderMapResult.get("trade_type"));

            //预支付交易链接
            resultMap.put("prepay_id",unifyOrderMapResult.get("prepay_id"));

            //二维码链接
            resultMap.put("code_url",unifyOrderMapResult.get("code_url"));

            //返回统一预支付成功
            return ResultBuildUtil.success(resultMap);

        }
        //统一下单失败
        return ResultBuildUtil.fail(unifyOrderMapResult.get("return_code"),unifyOrderMapResult.get("return_msg"));

    }

    /**
     * @author : Administrator
     * @date   : 2022/11/17
     * @param  : [request, response]
     * @return : void
     * @description : 接收用户支付成功后，微信异步回调支付结果
     */
    @RequestMapping("/wxpay/notifyresult")
    @ApiOperation(value = "异步回调待办",hidden = true)
    public void receiveWechatPayNotifyResult(HttpServletRequest request, HttpServletResponse response){

        //支付完成后，微信会把相关支付结果及用户信息通过数据流的形式发送给商户，商户需要接收处理，并按文档规范返回应答。

        try(InputStream inputStream = request.getInputStream()){

            //解析回调数据流
            BufferedReader brf = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            //定义可变字符对象，保存返回的xml格式支付结果
            StringBuilder wxpayNotifyXmlResult = new StringBuilder();

            //逐行解析
            String readline = null;
            while ((readline = brf.readLine()) != null){
                wxpayNotifyXmlResult.append(readline);
            }

            log.info("------ 3.微信支付结果异步回调内容：{} ------",wxpayNotifyXmlResult);


            //调用业务接口，解析异步回调的支付结果，并获取通知微信官方的结果
            String respWechatXmlResult = wechatPayService.getReturnWechatXllResult(wxpayNotifyXmlResult.toString());

            //同步给微信官方响应结果
            PrintWriter out = response.getWriter();
            out.write(respWechatXmlResult);
            out.flush();
            out.close();

            log.info("------ 4、微信支付异步回调处理后，响应结果：{} ------",respWechatXmlResult);

        }catch (Exception e){

            log.info("------ 微信支付结果异步回调处理异常，异常信息：{} ------", e.getMessage());
            log.error(e.toString());

        }
    }
    /**
     * @author : Administrator
     * @date   : 2022/11/17
     * @param  : [userVo]
     * @return : RequestReturn<String>
     * @description : 查询当前用户的会员到期时间
     */
    @PostMapping("/queryUserMemberDate")
    @ApiOperation(value = "查询会员时间",notes = "会员到期时间")
    public RequestResult<String> queryUserMemberDate(@RequestBody UserVO userVo){
        if (wechatPayService.findUserMemberDate(userVo) == null){
            return ResultBuildUtil.success("您不是会员，请购买会员后重试！");
        }
        return ResultBuildUtil.success("您的会员到期时间为：" + wechatPayService.findUserMemberDate(userVo));
    }

}
